package blog.utils;

import com.alibaba.fastjson.JSON;

import blog.service.OptionsService;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author Administrator
 * @date 2019/1/23 15:18
 */
@Service
public class DataMapUtil {
    @Autowired
    private OptionsService testService;

    private static final Logger LOGGER = LoggerFactory.getLogger(DataMapUtil.class);
    /**
     * 自动刷新时间（单位为秒）
     */
    private static final Integer EXPIRE_SENCOND = 60 * 60;
    /**
     * 存储数据的容器
     */
    private static final ConcurrentHashMap<String, String> DATA_MAP = new ConcurrentHashMap<>();

    /**
     * 缓存数据key
     */
    public static final String TEST_LIST = "test_list";

    /**
     * 获取全部缓存数据
     */
    public Map<String, String> getDataMap() {
        return DATA_MAP;
    }

    /**
     * Spring Bean创建之后执行的方法
     */
    @PostConstruct
    public void initMethod() {
        ExecutorService pool = new ThreadPoolExecutor(1, 1, 0L,
                TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(1),
                new BasicThreadFactory.Builder().namingPattern("data-map-pool-%d").daemon(true).build(),
                new ThreadPoolExecutor.AbortPolicy());
        pool.execute(new Task());
        pool.shutdown();
    }

    /**
     * 初始化方法，查询数据库数据储存到map中
     */
    private void initDataMap() {
        // test表数据
        setDataMap(TEST_LIST, testService.getOptions());
    }

    /**
     * 获取map缓存的对象
     */
    public static <T> T getObject(String key, Class<T> clazz) {
        return json2Object(DATA_MAP.get(key), clazz);
    }

    public static <T> List<T> getList(String key, Class<T> clazz) {
        return json2List(DATA_MAP.get(key), clazz);
    }

    private <T> void setDataMap(String key, T value) {
        DATA_MAP.put(key, object2Json(value));
    }

    private <T> void setDataMap(String key, List<T> value) {
        DATA_MAP.put(key, list2Json(value));
    }

    /**
     * json转换为Object
     */
    public static <T> T json2Object(String json, Class<T> clazz) {
        try {
            return JSON.parseObject(json, clazz);
        } catch (Exception e) {
            LOGGER.error("{} 转 JSON 失败", json);
        }
        return null;
    }

    /**
     * 对象转json
     */
    public static <T> String object2Json(T object){
        String json = JSON.toJSONString(object);
        return json;
    }

    /**
     * list转json
     */
    public static <T> String list2Json(List<T> list) {
        String jsons = JSON.toJSONString(list);
        return jsons;
    }

    /**
     * 获取key对应的List集合
     */
    public static <T> List<T> json2List(String json, Class<T> clazz) {
        List<T> list = JSON.parseArray(json, clazz);
        return list;
    }

    /**
     * 初始化及定时刷新
     */
    class Task implements Runnable {
        @Override
        public void run() {
            while (true) {
                initDataMap();
                LOGGER.info("###################初始化数据#######################");
                try {
                    Thread.sleep(EXPIRE_SENCOND * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

